const { Sequelize } = require("sequelize");
const { sequelize } = require("@core/db");
const Router = require("koa-router");

const { Order } = require("@models/order");
const { Auth } = require("@middlewares/auth");
const { Goods } = require("@models/goods");
const { Address } = require("@models/address");
const { operatorPoint } = require("@services/operatorPoint");
const { ImgService } = require("@services/img");

const router = new Router({
  prefix: "/v1/user/order",
});


// 获取订单列表
router.post("/list", new Auth().m, async (ctx, next) => {
  const { page = 1, pageSize = 10, order_status } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  const where = order_status
    ? { uid: ctx.auth.uid, order_status }
    : { uid: ctx.auth.uid };

  const { count: total, rows } = await Order.findAndCountAll({
    where,
    offset,
    limit: pageSize,
    order: [["created_at", "DESC"]],
    include: [
      {
        model: Goods,
        required: false,
      },
    ],
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 获取订单详情
router.post("/detail", new Auth().m, async (ctx, next) => {
  const { order_id } = ctx.request.body;
  const data = await Order.findOne({
    where: { order_id },
    include: [
      {
        model: Goods,
        where: { goods_id: Sequelize.col("Order.goods_id") },
        required: false,
      },
    ],
  });
  if (!data) {
    throw new global.errs.AuthFailed("订单不存在");
  }
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data,
  };
});

// 创建订单
router.post("/create", new Auth().m, async (ctx, next) => {
  const { address_id, goods_id, order_remark } = ctx.request.body;
  const t = await sequelize.transaction();

  const goods = await Goods.findOne({
    where: { goods_id },
  });
  if (!goods) {
    throw new global.errs.AuthFailed("商品不存在");
  }

  const getPoint_count = await operatorPoint.getPoint_count(ctx.auth.uid);
  if (getPoint_count - goods.price < 0) {
    throw new global.errs.AuthFailed("积分不足");
  }

  if (goods.goods_stock <= 0) {
    throw new global.errs.AuthFailed("商品库存不足");
  }

  // 更新库存
  await Goods.update(
    { goods_stock: Sequelize.literal("goods_stock - 1") },
    { where: { goods_id } },
    { transaction: t }
  );
  let { goods_details, goods_img, ...goods_data } = JSON.parse(
    JSON.stringify(goods)
  );
  goods_data.goods_img = await ImgService.getImg64(goods_img);
  const address_info = await Address.findOne({
    where: { address_id },
  });
  let address = JSON.stringify(address_info);
  const data = await Order.create(
    {
      address,
      goods_id,
      order_remark,
      goods_details: JSON.stringify(goods_data),
      uid: ctx.auth.uid,
    },
    { transaction: t }
  );
  if (!data) {
    await t.rollback();
    throw new global.errs.AuthFailed("创建失败");
  }
  await t.commit();

  // 消费积分
  await operatorPoint.consume_point(ctx.auth.uid, "兑换消耗", goods.price);

  ctx.body = {
    code: 200,
    msg: "创建成功",
    data,
  };
});

module.exports = router;
